<?php

namespace App\Http\Requests;

use App\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class DoctorUpdateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     * @return bool
     */
    public function authorize()
    {
        $user = \Auth::user();

        return $user && $user->isA('nurse');
    }

    public function withValidator(Validator $validator)
    {
        $validator->after(function (Validator $validator) {
            if ($validator->messages()->isEmpty()) {
                $exists = User::where('phone', $this->input('phone'))
                              ->where('id', '<>', $this->input('id'));;

                if ($exists->exists()) {
                    $validator->messages()->add('phone', '手机号已被占用。');
                }
            }
        });
    }

    /**
     * Get the validation rules that apply to the request.
     * @return array
     */
    public function rules()
    {
        return [
            'id'          => 'required|numeric',
            'name'        => 'required|alpha|max:16',
            'phone'       => [
                'required',
                'regex:/^1(3|4|5|7|8|9)\\d{9}$/',
            ],
            'password'    => 'alpha_dash|min:6|max:16',
            'role'        => 'required|in:doctor,nurse',
            'hospital_id' => 'required|integer|min:1',
            'job'         => 'in:' . implode(',', array_keys(config('custom.doctor.title'))),
        ];
    }
}
